package com.xinruke.hostels.systemmanage.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.common.cache.ManageUserCache;
import com.xinruke.hostels.common.cache.vo.LoginManageResultVO;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.YewuyonghuCaozuoRizhi;
import com.xinruke.hostels.common.po.YwFangjian;
import com.xinruke.hostels.common.po.YwLouceng;
import com.xinruke.hostels.common.service.OperateLogService;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.system.manage.interfaces.dto.*;
import com.xinruke.hostels.systemmanage.mapper.YwFangjianMapper;
import com.xinruke.hostels.systemmanage.mapper.YwLoucengMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 楼层管理
 *
 * @author Jinz
 * @date 2019-06-26 17:30
 */
@Service
@Slf4j
public class FloorService {
    @Autowired
    private YwLoucengMapper ywLoucengMapper;

    @Autowired
    private YwFangjianMapper fangjianMapper;

    @Autowired
    private RoomService roomService;

    @Autowired
    private ManageUserCache manageUserCache;

    @Autowired
    OperateLogService operateLogService;

    @Transactional(rollbackFor = Exception.class)
    public ResultVO add(FloorAddQueryDTO params) {
        ResultVO resultVO = ResultVO.fail();

        if (params.getLouchengkaishi() > params.getLouchengjieshu()) {
            resultVO.setMessage("楼层开始不能大于结束");
            return resultVO;
        }

        LoginManageResultVO userInfo = manageUserCache.getLoginManageUserInfo();

        for (int i = params.getLouchengkaishi(); i <= params.getLouchengjieshu(); i++) {
            //该楼层已存在
            QueryConditions queryConditions = new QueryConditions();
            queryConditions.addCondition("loucenghao", EConditionOperator.EQULS, i);
            queryConditions.addCondition("loudongId", EConditionOperator.EQULS, params.getLoudongId());
            queryConditions.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
            MyExample myExample = new MyExample(YwLouceng.class, queryConditions);
            List<YwLouceng> loucengList = ywLoucengMapper.selectByExample(myExample);
            if (!CollectionUtils.isEmpty(loucengList)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                resultVO.setMessage("该楼层已存在");
                return resultVO;
            }

            YwLouceng ywLouceng = new YwLouceng();
            BeanUtils.copyProperties(params, ywLouceng);
            ywLouceng.setLoucenghao(i);
            ywLouceng.setMingcheng(i + "楼");
            ywLouceng.setJiudianId(userInfo.getJiudianId());
            ywLouceng.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
            ywLouceng.setChuangjianrenId(userInfo.getId());
            ywLouceng.setChuangjianshijian(new Date());
            ywLouceng.setGengxinrenId(userInfo.getId());
            ywLouceng.setGengxinshijian(new Date());
            int check = ywLoucengMapper.insert(ywLouceng);
            if (check <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultVO.fail();
            }
        }
        resultVO = ResultVO.success();

        return resultVO;
    }

    public ResultVO modify(FloorUpdateQueryDTO floorUpdateQueryDTO) {
        ResultVO resultVO;
        YwLouceng ywLouceng = new YwLouceng();

        BeanUtils.copyProperties(floorUpdateQueryDTO, ywLouceng);
        ywLouceng.setGengxinrenId(manageUserCache.getCurrentUserId());
        ywLouceng.setGengxinshijian(new Date());
        try {
            int check = ywLoucengMapper.updateByPrimaryKeySelective(ywLouceng);
            if (check > 0) {
                resultVO = ResultVO.success();
            } else {
                resultVO = ResultVO.fail();
            }
        } catch (Exception e) {
            resultVO = ResultVO.fail();
            log.error("楼层修改异常，楼层信息为={}", JSONObject.toJSON(ywLouceng), e);
        }
        return resultVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVO delete(FloorDelQueryDTO floorDelQueryDTO) {
        ResultVO resultVO = ResultVO.fail();

        int loucengId = floorDelQueryDTO.getId();

        //删除所有的楼层
        YwLouceng louceng = new YwLouceng();
        louceng.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        louceng.setGengxinrenId(manageUserCache.getCurrentUserId());
        louceng.setGengxinshijian(new Date());

        QueryConditions loucengQueryCondition = new QueryConditions();
        loucengQueryCondition.addCondition("id", EConditionOperator.EQULS, loucengId);
        loucengQueryCondition.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        MyExample loucengMyExample = new MyExample(YwLouceng.class, loucengQueryCondition);
        int loucengRet = ywLoucengMapper.updateByExampleSelective(louceng, loucengMyExample);
        if (loucengRet <= 0) {
            log.error("删除楼层失败，楼层id[" + loucengId + "]");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            resultVO.setMessage("删除楼层失败");
            return resultVO;
        }

        //删除所有的房间
        YwFangjian fangjian = new YwFangjian();
        fangjian.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        fangjian.setGengxinrenId(manageUserCache.getCurrentUserId());
        fangjian.setGengxinshijian(new Date());

        QueryConditions fangjianQueryCondition = new QueryConditions();
        fangjianQueryCondition.addCondition("loucengId", EConditionOperator.EQULS, loucengId);
        fangjianQueryCondition.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        MyExample fangjianMyExample = new MyExample(YwFangjian.class, fangjianQueryCondition);
        fangjianMapper.updateByExampleSelective(fangjian, fangjianMyExample);

        //写入操作日志
        YewuyonghuCaozuoRizhi yewuyonghuCaozuoRizhi = new YewuyonghuCaozuoRizhi("楼层", "删除楼层", "楼层id[" + loucengId + "]");
        operateLogService.writeOperateLog(yewuyonghuCaozuoRizhi);

        resultVO = ResultVO.success();

        return resultVO;
    }

    public ResultVO<FloorDetailQueryResultDTO> detail(FloorDetailQueryDTO params) {

        ResultVO<FloorDetailQueryResultDTO> resultVO = ResultVO.success();

        YwLouceng param = new YwLouceng();
        param.setId(params.getId());
        YwLouceng ywLouceng = ywLoucengMapper.selectByPrimaryKey(param);
        FloorDetailQueryResultDTO floorDetailQueryResultDTO = new FloorDetailQueryResultDTO();
        BeanUtils.copyProperties(ywLouceng, floorDetailQueryResultDTO);

        List<RoomCountByFangxingResultDTO> roomTypeDetail = roomService.countByFangxing(params.getId());
        floorDetailQueryResultDTO.setRoomCountByFangxingResultDTOList(roomTypeDetail);
        resultVO.setData(floorDetailQueryResultDTO);
        return resultVO;
    }

    public ResultVO<RowsDataVO<FloorDetailQueryResultDTO>> floors(FloorsQueryDTO params) {

        RowsDataVO<FloorDetailQueryResultDTO> dataVO = new RowsDataVO<>();
        QueryConditions conditions = new QueryConditions();
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        conditions.addCondition("loudongId", EConditionOperator.EQULS, params.getLoudongId());
        conditions.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());

        MyExample example = new MyExample(YwLouceng.class, conditions, params.getOrderFields());
        Page<FloorDetailQueryResultDTO> page = PageHelper.startPage(params.getPageNo(), params.getPageSize());
        List<YwLouceng> ywLoucengs = ywLoucengMapper.selectByExample(example);

        List<FloorDetailQueryResultDTO> resultList = ywLoucengs.stream().map(n -> {
            FloorDetailQueryResultDTO louCeng = new FloorDetailQueryResultDTO();
            BeanUtils.copyProperties(n, louCeng);
            return louCeng;
        }).collect(Collectors.toList());
        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(resultList);

        ResultVO<RowsDataVO<FloorDetailQueryResultDTO>> result = ResultVO.success();
        result.setData(dataVO);
        return result;
    }

    public Integer count(FloorsCountQueryDTO params) {
        YwLouceng ywLouceng = new YwLouceng();
        ywLouceng.setLoudongId(params.getLoudongId());
        ywLouceng.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
        return ywLoucengMapper.selectCount(ywLouceng);
    }
}
